package cn.itcast.activemq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class TopicConsumer {
    public static void main(String[] args) throws Exception {
        //1. 创建连接工厂
        ConnectionFactory factory =
                new ActiveMQConnectionFactory("admin","admin","tcp://192.168.12.132:61616");
        //2. 根据连接工厂，创建连接对象(javax.jms.Connection)
        Connection conn = factory.createConnection();

        //3. 开启连接
        conn.start();

        //4. 创建session
        Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //5. 创建队列目的地对象
        Topic topic = session.createTopic("sms");

        //6. 创建消息的消费者
        MessageConsumer consumer = session.createConsumer(topic);

        //7. 创建消息的监听器，监听容器中的消息，实现消息消费
        consumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                // 转换
                MapMessage msg = (MapMessage) message;
                try {
                    // 获取消息内容，消费消息
                    System.out.println("消费消息,发短信：" + msg.getString("phone"));
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
